package com.njit.mailm.core.service.impl;

import com.njit.mailm.core.bean.MessageWrap;
import com.njit.mailm.core.service.SendService;
import com.sun.corba.se.spi.servicecontext.SendingContextServiceContext;
import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.apache.commons.mail.MultiPartEmail;
import org.springframework.stereotype.Service;

/**
 * Created by Administrator on 2016/5/4.
 */

@Service
public class SendServiceImpl implements SendService {
    /**
     * 发送html邮件
     * @param msg
     * @throws Exception
     */
    public void sendHtmlEmail(MessageWrap msg) throws Exception {
        HtmlEmail email = new HtmlEmail();// 构造一个html mail对象
        email.setHostName(msg.getEmail().getSmtp().getIp()); // 发送服务器
        email.setAuthentication(msg.getEmail().getAccount(), msg.getEmail().getPassword()); // 发送邮件的用户名和密码
        try {
            email.addTo(msg.getTos());// 设置发送对象
            if (msg.getCcs() != null && msg.getCcs().length > 0 ) {
                email.addCc(msg.getCcs());
            }
            if (msg.getBccs() != null && msg.getBccs().length > 0) {
                email.addBcc(msg.getBccs());
            }
            email.setFrom(msg.getEmail().getAccount(),msg.getEmail().getAccount());// 设置发送人
            email.setSubject(msg.getSubject());// 设置主题
            String mag = msg.getBody();// 这里可以写你的html文档,因为本页面我是用xml文件做数据存储的,不能写标签,这里我就不写了
            email.setHtmlMsg(mag);// 设置内容
            email.setCharset("UTF-8");// 设置字符集
            email.send();// 发送
        } catch (EmailException e) {
            e.printStackTrace();
        }
    }

    public void sendAttachmentEmail(MessageWrap messageWrap) throws Exception {
        // Create the attachment
        EmailAttachment attachment = new EmailAttachment();
        attachment.setPath("mypictures/john.jpg");
        attachment.setDisposition(EmailAttachment.ATTACHMENT);
        attachment.setDescription("Picture of John");
        attachment.setName("John");

        // Create the email message
        MultiPartEmail email = new MultiPartEmail();
        email.setHostName("mail.myserver.com");
        email.addTo("jdoe@somewhere.org", "John Doe");
        email.setFrom("me@apache.org", "Me");
        email.setSubject("The picture");
        email.setMsg("Here is the picture you wanted");

        // add the attachment
        email.attach(attachment);

        // send the email
        email.send();
    }
}
